// 参考自：如何用Momentjs精确计算年龄
// https://cloud.tencent.com/developer/ask/153883

import { message } from "antd";
import { json, save, dele, jobs } from "../services/info";
import moment from 'moment';

export default {
  namespace: "info",

  // 状态机
  state: {
    data: [], // 表格数据
    total: 0, // 表格记录条数
    success: true, // 操作是否成功(保存和删除是否成功)
    jobData: [], // 岗位数据
    jobMapping: {}, // 根据岗位id获取岗位名称
  },

  // 发起网络请求
  effects: {
    *json({ payload }, { call, put }) {
      const response = yield call(json, payload);
      yield put({ type: "callbackJson", response });
    },
    *save({ payload }, { call, put }) {
      const response = yield call(save, payload);
      yield put({ type: "callbackSave", response });
    },
    *dele({ payload }, { call, put }) {
      const response = yield call(dele, payload);
      yield put({ type: "callbackDele", response });
    },
    *jobs({ payload }, { call, put }) {
      const response = yield call(jobs, payload);
      yield put({ type: "callbackJobs", response });
    },
  },

  // 回调处理
  reducers: {
    callbackJson(st, { response }) {
      const state = st;
      if (response.success) {
        state.data = response.root.map((item) => {
          let { pay0, pay1, cashPledgeNum, jobId, birthday } = item;
          pay0 -= 0;
          pay1 -= 0;
          cashPledgeNum -= 0;

          return {
            ...item,
            pay0,
            pay1,
            cashPledgeNum,
            jobName: state.jobMapping[jobId],
            // 根据出生日期获取年龄
            age: moment.duration(moment().diff(birthday)).years(),
          };
        });
        state.total = response.total;
      } else if (response.status === 1) message.error(response.msg);
      return { ...state };
    },
    callbackDele(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) {
        message.success(response.msg);
      } else if (response.status === 1) message.error(response.msg);
      return { ...state };
    },
    callbackSave(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) {
        message.success(response.msg);
      } else if (response.status === 1) message.error(response.msg);
      return { ...state };
    },
    callbackJobs(st, { response }) {
      const state = st;
      if (response.success) {
        state.jobData = response.root.sort((a, b) => b.sequ - a.sequ);
        for (let i = 0; i < state.jobData.length; i += 1) {
          const item = state.jobData[i];
          const { id, name } = item;
          state.jobMapping[id] = name;
        }
      } else if (response.status === 1) message.error(response.msg);
      return { ...state };
    },
  },
};
